iT邦幫忙

2022 iThome 鐵人賽

DAY 22
0
Software Development

30而Leet{code}系列 第 22

D22 - [String] First Unique Character in a String

  • 分享至 

  • xImage
  •  

我明明 Filter 題目時有 apply tag "Stack",結果做一做發現今天的題目根本不需要 Stack...

問題

https://leetcode.com/problems/first-unique-character-in-a-string

Given a string s, find the first non-repeating character in it and return its index. If it does not exist, return -1.

Example 1:
Input: s = "leetcode"
Output: 0

Example 2:
Input: s = "loveleetcode"
Output: 2

Example 3:
Input: s = "aabb"
Output: -1

Constraints:

  • 1 <= s.length <= 105
  • s consists of only lowercase English letters.

提示

Python's Counter

https://realpython.com/python-counter/

Python 可以用 collections 裡面的 Counter 函式來計算物件出現的次數,因為這個函式裡面是用 C 語言實作,所以會比自己用 dict 計算次數來得快.

>>> from collections import Counter

>>> # Use a string as an argument
>>> Counter("mississippi")
Counter({'i': 4, 's': 4, 'p': 2, 'm': 1})

我的答案

Python

from collections import Counter
class Solution:
    def firstUniqChar(self, s: str) -> int:
        count = Counter(s)
        indexes = [s.index(letter) for letter in count if count[letter] == 1]
        return min(indexes) if indexes else -1

Go 沒有 Counter 函式可以用.必須用 HashMap 來計算次數.

func firstUniqChar(s string) int {
    count := map[rune]int{}

	for _, letter := range s {
		count[letter]++
	}

	for index, letter := range s {
		if count[letter] == 1 {
			return index
		}
	}

	return -1
}

上一篇
D21 - [Stack] Valid Parentheses
下一篇
D23 - [Stack] Next Greater Element I
系列文
30而Leet{code}30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言